import type { SysListUserParamsType, SysListUserType, SysUserWriteParamsType } from './model'
import {
  addSysUserAPI,
  deleteSysUserAPI,
  exportUserExcelAPI,
  getUserListAPI,
  updateSysUserAPI
} from './api'
import type { SpColumnsType } from '@/components/SpTable/type'
import { Avatar, message, Tag } from 'ant-design-vue'
import { addDialog } from '@/components/SpDialog/index'
import ModalForm from '../form/modal.vue'
import type { FormExpose } from 'ant-design-vue/es/form/Form'
import { formatFileUrl } from '@/utils/fileUtils'
import { exportExcel } from '@/views/admin/exportExcel/exportExcel'
import { getDeptTreeAPI } from '@/views/admin/system/dept/utils/api'
import type { SysDeptListType } from '@/views/admin/system/dept/utils/model'
import type { SysPostListType } from '@/views/admin/system/post/utils/model'
import { getPostListAPI } from '@/views/admin/system/post/utils/api'
import type { SysRoleListType } from '@/views/admin/system/role/utils/model'
import { getRoleListAPI } from '@/views/admin/system/role/utils/api'

export function useUser() {
  // 表格列
  const columns: SpColumnsType[] = [
    {
      title: 'id',
      dataIndex: 'id',
      width: 100,
      align: 'center'
    },
    {
      title: '微信ID',
      dataIndex: 'openId',
      width: 150,
      align: 'center'
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      cellRenderer: (record: SysListUserType) => {
        return <Avatar src={formatFileUrl(record.avatar)} size={50} />
      },
      width: 70,
      align: 'center'
    },
    {
      title: '昵称',
      dataIndex: 'name',
      width: 100,
      align: 'center'
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 100,
      align: 'center'
    },
    {
      title: '部门名',
      dataIndex: 'deptName',
      width: 100,
      align: 'center'
    },

    {
      title: '性别',
      dataIndex: 'sex',
      width: 100,
      cellRenderer: (record: SysListUserType) => {
        if (record.sex === 0) {
          return <Tag color="red">女</Tag>
        } else {
          return <Tag color="green">男</Tag>
        }
      },
      align: 'center'
    },
    {
      title: '角色',
      dataIndex: 'roles',
      cellRenderer: (record: SysListUserType) => {
        if (record.roles) {
          return (
            <div
              style={{
                display: 'flex',
                flexWrap: 'wrap',
                justifyContent: 'center',
                alignContent: 'center'
              }}
            >
              {record.roles.split(',').map((item: string) => (
                <Tag style={{ marginBottom: '5px' }} color={'green'}>
                  {item}
                </Tag>
              ))}
            </div>
          )
        } else {
          return <Tag>暂无</Tag>
        }
      },
      width: 200,
      align: 'center'
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
      width: 100,
      align: 'center'
    },
    {
      title: '岗位',
      dataIndex: 'posts',
      cellRenderer: (record: SysListUserType) => {
        if (record.posts) {
          return (
            <div
              style={{
                display: 'flex',
                flexWrap: 'wrap',
                justifyContent: 'center',
                alignContent: 'center'
              }}
            >
              {record.posts.split(',').map((item: string) => (
                <Tag style={{ marginBottom: '5px' }} color={'green'}>
                  {item}
                </Tag>
              ))}
            </div>
          )
        } else {
          return <Tag>暂无</Tag>
        }
      },
      width: 200,
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status',
      cellRenderer: (record: SysListUserType) => {
        if (record.status === 0) {
          return <Tag color="red">禁用</Tag>
        } else {
          return <Tag color="green">正常</Tag>
        }
      },
      width: 100,
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 200,
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'operation',
      fixed: 'right',
      width: 120,
      align: 'center'
    }
  ]
  // 查询参数
  const [queryParams, reset] = useResetState<SysListUserParamsType>(
    {
      pageNum: 1,
      pageSize: 5,
      total: 0
    },
    () => {
      getDataList()
    }
  )
  // 表格数据
  const { getDataList, dataList, loading, paginationChange } = useTablePaging(
    getUserListAPI,
    queryParams
  )
  // 选中项
  const selectedRowKeys = ref<number[]>([])
  // 角色列表数据
  const roleList = ref<SysRoleListType[]>([])
  // 岗位列表数据
  const postList = ref<SysPostListType[]>([])
  // 部门树
  const treeData = ref<SysDeptListType[]>([])
  // 弹窗框Ref
  const modalRef = ref()

  /** 获取角色列表 */
  function getRoleList() {
    getRoleListAPI({ pageNum: 1, pageSize: 99999 }).then((res) => {
      roleList.value = res.data.rows
    })
  }

  /** 获取岗位列表 */
  function getPostList() {
    getPostListAPI({ pageNum: 1, pageSize: 99999 }).then((res) => {
      postList.value = res.data.rows
    })
  }

  // 获取部门树数据
  function getDeptTreeData() {
    getDeptTreeAPI().then((res) => {
      treeData.value = res.data
    })
  }

  // 打开弹窗
  function openModal(title: '新增' | '编辑', data?: SysListUserType) {
    addDialog({
      title: `${title}用户`,
      width: '50%',
      contentRenderer: () =>
        h(ModalForm, {
          ref: modalRef,
          roleList: roleList.value,
          postList: postList.value,
          treeData: treeData.value,
          id: data?.id
        }),
      beforeSure: function (done) {
        // 关闭弹窗
        function chores(title: string, name: string, done: Function) {
          message.success(`您${title}了用户名称为${name}的这条数据`)
          done()
          getDataList()
        }
        const form = modalRef.value.getRef() as FormExpose
        form.validate().then((res) => {
          const formData = res as SysUserWriteParamsType
          if (title == '编辑') {
            updateSysUserAPI(data?.id as number, formData).then(() => {
              chores(title, formData.username, done)
            })
          } else {
            addSysUserAPI(formData).then(() => {
              chores(title, formData.username, done)
            })
          }
        })
      }
    })
  }

  // 删除
  const deleteData = (data: SysListUserType) => {
    deleteSysUserAPI(data.id as number).then(() => {
      message.success(`删除成功`)
      getDataList()
    })
  }

  // 批量删除
  function batchDeleteChange() {}

  /** 导出数据 */
  function exportData(ids: number[], c: SpColumnsType[]) {
    exportExcel(
      {
        total: queryParams.total as number,
        queryParams: queryParams.value,
        selectedRowKeys: ids,
        columns: c
      },
      exportUserExcelAPI
    )
  }

  //选上部门
  function selectTree(value: number | undefined) {
    queryParams.deptId = value
    getDataList()
  }

  // 选中项
  const onSelectChange = (keys: number[]) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys)
    selectedRowKeys.value = keys
  }

  // 搜索
  function search() {
    getDataList()
  }

  onMounted(() => {
    getRoleList()
    getPostList()
    getDeptTreeData()
    getDataList()
  })

  return {
    dataList,
    queryParams,
    columns,
    loading,
    roleList,
    selectedRowKeys,
    postList,
    treeData,
    selectTree,
    paginationChange,
    search,
    reset,
    batchDeleteChange,
    onSelectChange,
    openModal,
    deleteData,
    exportData
  }
}
